<template>
  <div class="box">

    <div class="card1">

      <div class="parent">
        <h3>商品管理</h3>
        <el-divider></el-divider>
        <el-form :inline="true" :model="formInline" ref="formInline" class="demo-form-inline" size="small">
          <el-form-item label="鲜花名称" prop="flowerName">
            <el-input v-model="formInline.flowerName" placeholder="请输入鲜花名称"></el-input>
          </el-form-item>
          <el-form-item label="上架时间" prop="publishedDate">
            <el-date-picker
                v-model="formInline.publishedDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <p></p>
          
          <el-form-item label="商品状态" prop="isDelete">
            <el-select v-model="formInline.isDelete" placeholder="请选择商品状态" style="width: 190px;">
              <el-option label="待上架" value="2"></el-option>
              <el-option label="已删除" value="1"></el-option>
              <el-option label="供货中" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="selectAllFlowerInfo">查询</el-button>
            <el-button type="info" icon="el-icon-refresh-right" @click="resetInfo">重置</el-button>
          </el-form-item>
        </el-form>
        <div align="right" style="position: absolute;top:250px;right: 150px;">
          
          <el-button type="info" icon="el-icon-plus" @click="addFlowerInfo" size="small">添加商品</el-button>
          <el-button type="success" icon="el-icon-plus" @click="showFlowerByIsDelete(2)" size="small">批量上架</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="showFlowerByIsDelete(1)" size="small">批量删除</el-button>
          <el-button type="warning" icon="el-icon-sold-out"  @click="showFlowerByIsDelete(0)" size="small">批量下架</el-button>
        </div>
        <el-divider></el-divider>
        <!--订单表格-->
        <el-table :data="FlowerInfoData" stripe border style="width: 100%">
          <el-table-column prop="flowerId" label="鲜花编号"  align="center"></el-table-column>
          <el-table-column prop="flowerName" label="鲜花名称"  align="center"></el-table-column>
          <el-table-column prop="flowerImg" label="鲜花图片"  align="center">
            <template slot-scope="{row}">
              <img :src="`http://localhost:8088/image/${row.flowerImg}`" style="width: 80px;height: 80px;">
            </template>
          </el-table-column>
          <el-table-column prop="typeName" label="鲜花类型"  align="center"></el-table-column>
          <el-table-column prop="publisherDate" label="上架时间"  align="center">
            <template slot-scope="{row}">
              <span v-if="row.publisherDate===null">未上架</span>
              <span v-else>{{row.publisherDate}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="flowerPrice" label="鲜花单价(元)" align="center"></el-table-column>
          <el-table-column prop="flowerStoreCount" label="库存数量" align="center"></el-table-column>
          <el-table-column prop="flowerSaleCount" label="销售数量" align="center">
            <template slot-scope="{row}">
              <span v-if="row.flowerSaleCount===null">暂无</span>
              <span v-else>{{row.flowerSaleCount}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="flowerCollectionCount" label="收藏数量" align="center">
            <template slot-scope="{row}">
              <span v-if="row.flowerCollectionCount===null">暂无</span>
              <span v-else>{{row.flowerCollectionCount}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="introduction" label="鲜花介绍" align="center">
            <template slot-scope="{row}">
              <span v-if="row.introduction===null">暂无</span>
              <span v-else>{{row.introduction}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="isDelete" label="商品状态" align="center">
            <template slot-scope="{row}">
              <span v-if="row.isDelete === 0">供货中</span>
              <span v-if="row.isDelete === 1">已删除</span>
              <span v-if="row.isDelete === 2">待上架</span>
            </template>
          </el-table-column>
          
          <el-table-column label="商品操作" width="100" align="center">
            <template slot-scope="{row}">
              <div v-if="row.isDelete!==1">
              <el-button  type="text" size="small" @click="updateFlower(row)">更新商品</el-button>
              <br>
              <el-button type="text" size="small" style="color: #c02626" @click="updateIsDelete(row.flowerId,1)">删除商品</el-button>
              <br>
              <el-button type="text" size="small" style="color: chocolate" v-if="row.isDelete===0" @click="updateIsDelete(row.flowerId,2)">下架商品</el-button>
              <el-button type="text" size="small" style="color: cyan" v-if="row.isDelete===2" @click="updateIsDelete(row.flowerId,0)">上架商品</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-divider></el-divider>
        
        <!--商品模态框-->
        <el-dialog title="商品列表" :visible.sync="FlowerDialog"  width="65%" >
          <div style="font-size: 20px">全选
            <input type="checkbox" style="width: 16px;height: 16px" 
                   :checked="isAllSelected" 
                   @change="toggleAllSelection">
          </div>
          <el-divider></el-divider>
          <div v-for="(value,key) in FlowerPublishData" :key="key" style="display:inline-block;">
          <table  style="height: 150px;width: 300px;margin: 15px" class="table">
            <tr>
              <td rowspan="4" >
              <!--多选框-->
                <input type="checkbox"  style="width: 15px;height: 15px" :value="value.flowerId"
                       v-model="selectedFlowerId">
              </td>
              <!--图片-->
              <td rowspan="4">
                <el-avatar shape="square" :size="130" :src="`http://localhost:8088/image/${value.flowerImg}`"></el-avatar>
              </td>
            </tr>
            <tr><td style="color: cornflowerblue">鲜花名称:{{ value.flowerName }}</td></tr>
            <tr><td>鲜花编号:{{ value.flowerId }}</td></tr>
            <tr><td style="color: #c02626">鲜花单价:{{ value.flowerPrice }}元</td></tr>
          </table>
          </div>
          
          <!--对话框底部-->
          <span slot="footer" class="dialog-footer">
          <el-button @click="FlowerDialog = false">取 消</el-button>
          <el-button type="primary" @click="publishFlower">确 定</el-button>
          </span>
        </el-dialog>
        
        <!--添加鲜花表单模态框-->
          <el-dialog title="添加鲜花商品信息" :visible.sync="addFlowerDialog"  width="40%" >
            <el-form ref="flowerForm" :model="flowerForm" :rules="rules">
              <el-form-item label="商品名称" prop="flowerName">
                <el-input v-model="flowerForm.flowerName" style="width: 300px;" placeholder="请选择商品名称"></el-input>
              </el-form-item>
              <el-form-item label="商品类型" prop="typeId">
                <el-select v-model="flowerForm.typeId" placeholder="请选择鲜花类型" style="width: 300px;">
                  <el-option v-for="type in flowerTypes" :key="type._id" :label="type.typeName" :value="type.typeId"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="商品价格" prop="flowerPrice">
                <el-input v-model="flowerForm.flowerPrice" style="width: 300px;" placeholder="请选择商品价格"></el-input>
              </el-form-item>
              <el-form-item label="商品库存" prop="flowerStoreCount">
                <el-input v-model="flowerForm.flowerStoreCount" style="width: 300px;" placeholder="请选择商品库存"></el-input>
              </el-form-item>
              <el-form-item label="商品介绍" prop="introduction">
                <el-input
                    type="textarea"
                    placeholder="请输入对商品的介绍/限30字以内"
                    v-model="flowerForm.introduction"
                    maxlength="30"
                    show-word-limit
                    style="width: 500px;"
                ></el-input>
              </el-form-item>
              <el-form-item label="鲜花图片">
                <el-input type="text" style="display: none" v-model="flowerForm.flowerImg"></el-input>
              <el-upload
                  
                  action="http://localhost/flowerInfo/upload"
                  list-type="picture-card"
                  :on-success="handlePictureName"
                  :on-remove="handleRemove"
                  :on-exceed="handleExceed"
                  :limit="1">
                <i class="el-icon-plus"></i>
              </el-upload>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>

        <!--修改鲜花表单模态框-->
        <el-dialog title="更新鲜花商品信息" :visible.sync="updateFlowerDialog"  width="40%" :before-close="clearFileList">
          <el-form ref="flowerForm" :model="flowerForm" :rules="rules">
            <el-input v-model="flowerForm.flowerId" style="display: none" ></el-input>
            <el-form-item label="商品名称" prop="flowerName">
              <el-input v-model="flowerForm.flowerName" style="width: 300px;" placeholder="请选择商品名称"></el-input>
            </el-form-item>
            <el-form-item label="商品类型" prop="typeId">
              <el-select v-model="flowerForm.typeId" placeholder="请选择鲜花类型" style="width: 300px;" >
                <el-option v-for="type in flowerTypes" :key="type._id" :label="type.typeName" :value="type.typeId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品价格" prop="flowerPrice">
              <el-input v-model="flowerForm.flowerPrice" style="width: 300px;" placeholder="请选择商品价格"></el-input>
            </el-form-item>
            <el-form-item label="商品库存" prop="flowerStoreCount">
              <el-input v-model="flowerForm.flowerStoreCount" style="width: 300px;" placeholder="请选择商品库存"></el-input>
            </el-form-item>
            <el-form-item label="商品介绍" prop="introduction">
              <el-input
                  type="textarea"
                  placeholder="请输入对商品的介绍/限30字以内"
                  v-model="flowerForm.introduction"
                  maxlength="30"
                  show-word-limit
                  style="width: 500px;"
              ></el-input>
            </el-form-item>
            <el-form-item label="鲜花图片" prop="flowerImg">
<!--              <el-input type="text"  style="display: none"  v-model="flowerForm.oldflowerImg"></el-input>-->
              <el-input type="text"  style="display: none"  v-model="flowerForm.flowerImg"></el-input>
              <img :src="`http://localhost:8088/image/${flowerForm.flowerImg}`"  
                   style="max-width: 300px; max-height: 300px;"  onerror="this.style.display='none'"  onload="this.style.display='block'">
              <el-upload
                  action="http://localhost/flowerInfo/upload"
                  list-type="picture"
                  :on-success="handlePictureName"
                  :on-remove="handleRemove"
                  :on-exceed="handleExceed"
                  :limit="1" :file-list="flowerForm.fileList">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm">提交</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        
        <!--分页插件-->
        <el-pagination align="center"  style="margin-top:30px; "
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="pageNum"
                       :page-sizes="[5,10,15,20]"
                       :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total">
        </el-pagination>

      </div>
      <router-view/>
    </div>
  </div>
</template>

<script>

export default {
  name: "FlowerView",
  // 数据
  data() {
    return {
      pageNum:1,
      pageSize:5,
      total:0,
      
      formInline: {
        flowerName:'',
        publishedDate:[],
        isDelete:'',
      },
      
      //鲜花表单
      flowerForm:{
        flowerId:'',
        flowerName:'',
        typeId:'',
        flowerPrice:'',
        flowerStoreCount:'',
        introduction:'',
        //上传图片的名称
        flowerImg:'',
        fileList: [],
        oldflowerImg:'',
      },
      flowerTypes:[],
      
      rules:{
        flowerName: [
          { required: true, message: '请输入鲜花名称', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        typeId:[
          { required: true, message: '请选择鲜花种类', trigger: 'change' }
        ],
        flowerPrice: [
          { required: true, message: '请输入鲜花价格', trigger: 'blur' },
        ],
        flowerStoreCount: [
          { required: true, message: '请输入鲜花库存', trigger: 'blur' },
        ],
        introduction: [
          { required: true, message: '请填写30字以内对鲜花的介绍', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ],
      },
      
      //所有商品信息
      FlowerInfoData: [],
      //待上架商品信息
      FlowerPublishData: [],
      
      FlowerDialog: false,
      selectedFlowerId: [], // 单选选中的鲜花ID
      isAllSelected: false, // 全选状态
      isDelete:'',

      addFlowerDialog:false,
      updateFlowerDialog:false,
    }
  },
  // 方法
  methods: {
    // 图片删除
    handleRemove() {
      this.flowerForm.flowerImg = this.flowerForm.oldflowerImg;
    },
    //清除上传图片列表
    clearFileList(done){
      this.flowerForm.fileList = [];
      done();
    },
    //文件上传超过限制
    handleExceed(){
      this.$message.warning(`文件个数超出限制!`);
    },
    //图片上传成功后的返回图片名称
    handlePictureName(response){
      this.flowerForm.flowerImg = response;
    },
    //更新商品信息
    updateFlower(row){
      this.flowerForm = {...row};
      this.flowerForm.oldflowerImg = this.flowerForm.flowerImg;
      this.updateFlowerDialog = true;
    },

    addFlowerInfo(){
      this.flowerForm = {};
      this.addFlowerDialog =true;
    },
    
    handleSizeChange(val) {
      this.pageSize = val;
      this.selectAllFlowerInfo();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.selectAllFlowerInfo();
    },
    //批量操作商品
    publishFlower(){
      if (this.isDelete===2){
        this.$confirm("是否上架这些商品?")
            .then(()=>{
              for (const i of this.selectedFlowerId){
                this.$axios.get("/flowerInfo/updateFlowerInfoByFlowerIdToStatus",
                    {
                      params: {
                        flowerId: i,
                        isDelete: 0,
                      }
                    }
                ).then(()=>{
                  this.selectAllFlowerInfo();
                })
              }
              this.$message({
                type: "success",
                message: "上架商品成功",
              });
              this.FlowerDialog = false;
              this.selectedFlowerId=[];
              this.isAllSelected =false;
            }).catch(()=>{})
      }
      if (this.isDelete===1){
        this.$confirm("是否删除这些商品?")
            .then(()=>{
              for (const i of this.selectedFlowerId){
                this.$axios.get("/flowerInfo/updateFlowerInfoByFlowerIdToStatus",
                    {
                      params: {
                        flowerId: i,
                        isDelete: this.isDelete,
                      }
                    }
                ).then(()=>{
                  this.selectAllFlowerInfo();
                })
              }
              this.$message({
                type: "success",
                message: "删除商品成功",
              });
              this.FlowerDialog = false;
              this.selectedFlowerId=[];
              this.isAllSelected =false;
            }).catch(()=>{})
      }
      if (this.isDelete===0){
        this.$confirm("是否下架这些商品?")
            .then(()=>{
              for (const i of this.selectedFlowerId){
                this.$axios.get("/flowerInfo/updateFlowerInfoByFlowerIdToStatus",
                    {
                      params: {
                        flowerId: i,
                        isDelete: 2,
                      }
                    }
                ).then(()=>{
                  this.selectAllFlowerInfo();
                  
                })
              }
              this.$message({
                type: "success",
                message: "下架商品成功",
              });
              this.FlowerDialog = false;
              this.selectedFlowerId=[];
              this.isAllSelected =false;
            }).catch(()=>{})
      }
    },
    //全选商品
    toggleAllSelection() {
      this.isAllSelected = !this.isAllSelected;
      // 根据全选状态更新每个radio的选中状态
      if (this.isAllSelected) {
        this.selectedFlowerId = this.FlowerPublishData.map(item => item.flowerId);
      } else {
        this.selectedFlowerId = [];
      }
    },
    
    //查询所有商品信息
    selectAllFlowerInfo(){
      this.$axios.get("/flowerInfo/selectAllFlowerInfo",{
        params: {
          pageSize:this.pageSize,
          pageNum:this.pageNum,
          flowerName:this.formInline.flowerName,
          startTime:this.formInline.publishedDate[0]?this.formInline.publishedDate[0].getTime():null,
          endTime:this.formInline.publishedDate[1]?this.formInline.publishedDate[1].getTime():null,
          isDelete:this.formInline.isDelete,
  
      }}).then(response => {
        if (response.data.code === 200) {
          this.FlowerInfoData = response.data.data.list;
          this.pageNum = response.data.data.pageNum;
          this.pageSize = response.data.data.pageSize;
          this.total = response.data.data.total;
          this.$message({
            type: "success",
            message: "商品管理查询成功",
          })
        }
        
      });
    }, 
    
    resetInfo(){
      this.$refs.formInline.resetFields();
      this.selectAllFlowerInfo();
    },
    // 删除,下架,上架商品
    updateIsDelete(flowerId,isDelete){
      if (isDelete===2){
        this.$confirm('是否下架此商品？')
            .then(() => {
              this.$axios.get("/flowerInfo/updateFlowerInfoByFlowerIdToStatus",
                  {
                    params: {
                      flowerId: flowerId,
                      isDelete: isDelete,
                    }
                  }
              ).then(response => {
                console.log(response)
                this.$message({
                  type: "success",
                  message: "下架商品成功",
                });
                this.selectAllFlowerInfo();
              })
            }).catch(()=>{});
      }else if (isDelete===1) {
        this.$confirm('是否删除此商品？')
            .then(() => {
              this.$axios.get("/flowerInfo/updateFlowerInfoByFlowerIdToStatus",
                  {
                    params: {
                      flowerId: flowerId,
                      isDelete: isDelete,
                    }
                  }
              ).then(response => {
                console.log(response)
                this.$message({
                  type: "success",
                  message: "删除商品成功",
                });
                this.selectAllFlowerInfo();
              })
            }).catch(()=>{});
      }else if(isDelete===0) {
        this.$confirm('是否上架此商品？')
            .then(() => {
              this.$axios.get("/flowerInfo/updateFlowerInfoByFlowerIdToStatus",
                  {
                    params: {
                      flowerId: flowerId,
                      isDelete: isDelete,
                    }
                  }
              ).then(response => {
                console.log(response)
                this.$message({
                  type: "success",
                  message: "上架商品成功",
                });
                this.selectAllFlowerInfo();
              })
            }).catch(()=>{});
      }
    },
    //查询所有待上架商品信息
    showFlowerByIsDelete(isDelete){
      this.FlowerDialog = true;
      this.$axios.get("/flowerInfo/selectAllFlowerInfoByIsDelete",
          {
            params: {
              isDelete: isDelete,
            }
          })
          .then(response => {
            if (response.data.code === 200) {
              this.FlowerPublishData = response.data.data;
              this.isDelete = isDelete;
            }
          });
    },
    
    //查询所有商品分类
    selectAllFlowerType(){
      this.$axios.get("/flowerInfo/selectAllFlowerType")
          .then(response => {
            console.log(response)
            if (response.data.code === 200) {
              
              this.flowerTypes = response.data.data;
            }
          });
    },
    
    //提交表单
    submitForm() {
      this.$refs.flowerForm.validate((valid) => {
        if (valid) {
          console.log(this.flowerForm)
          let data = {
            "flowerId": this.flowerForm.flowerId,
            "flowerName": this.flowerForm.flowerName,
            "typeId": this.flowerForm.typeId,
            "flowerPrice": this.flowerForm.flowerPrice,
            "flowerStoreCount": this.flowerForm.flowerStoreCount,
            "introduction": this.flowerForm.introduction,
            "flowerImg": this.flowerForm.flowerImg,
            "isDelete": 2,
          }
          this.$axios.post("/flowerInfo/addFlowerInfo", data)
             .then(response => {
                
                if (response.data.code === 200) {
                  this.selectAllFlowerInfo();
                }
                this.$message({
                  type: "success",
                  message: response.data.message,
                });
                this.addFlowerDialog = false;
                this.updateFlowerDialog = false;
              })
             .catch(error => {
                console.log(error);
              });
        } 
      });
    },
    //重置表单
    resetForm() {
      this.$refs.flowerForm.resetFields();
    },
  },
  
  created() {
    this.selectAllFlowerInfo();
    this.selectAllFlowerType();
  },
}
</script>
<style scoped lang="less">
.box {
  border-radius: 4px;
  border: 1px solid white;
  background-color: white;
  margin: 30px 100px;
}

.box .card1 {
  margin: 20px 10px;
  text-align: left;
}
</style>